<template>
  <div class="search">
    <input class="search-input" v-model="keyword" type="text" placeholder="输入城市名称或拼音">
    <div class="search-content" ref="search" v-show="notInput">
      <ul>
        <li class="search-item border-bottom" @click="changeCity(item.name)" v-for="(item, index) in result" :key="index">
          {{item.name}}
        </li>
        <li v-if="notFoundCity">
          抱歉未检索到您所查找城市
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import Bscroll from 'better-scroll'
export default {
  name: 'CitySearch',
  props: {
    cities: Object
  },
  data () {
    return {
      keyword: '',
      result: [],
      timer: null
    }
  },
  methods: {
    changeCity (c) {
      this.$store.dispatch('switchCity', c)
      this.$router.push('/')
    }
  },
  computed: {
    notInput () {
      return this.keyword.length
    },
    notFoundCity () {
      return !this.result.length
    }
  },
  watch: {
    keyword: function () {
      if (!this.keyword) {
        this.result = []
      }
      if (this.timer) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(() => {
        const result = []
        for (let i in this.cities) {
          this.cities[i].forEach((val) => {
            if (val.spell.indexOf(this.keyword) > -1 || val.name.indexOf(this.keyword) > -1) {
              result.push(val)
            }
          })
        }
        this.result = result
      }, 100)
    }
  },
  mounted () {
    this.scroll = new Bscroll(this.$refs.search)
  }
}
</script>

<style lang="stylus" scoped>
  @import "~styles/varibles.styl"
  .search
    height: .72rem
    padding: 0 .1rem
    background: $bgColor
    .search-content
      z-index: 1
      overflow: hidden
      position: absolute
      top: 1.58rem
      left: 0
      right: 0
      bottom: 0
      background: #eee
      .search-item
        line-height: .62rem
        padding-left: .2rem
        color: #666
        background: #fff
    .search-input
      width: 100%
      height: .62rem
      line-height: .62rem
      -webkit-border-radius: .06rem
      -moz-border-radius: .06rem
      border-radius: .06rem
      padding: 0 .1rem
      -webkit-box-sizing: border-box
      -moz-box-sizing: border-box
      box-sizing: border-box
      color: #666
      text-align: center
</style>
